const express = require("express");
const path=require('path')
const cors = require("cors");
const DBService = require("./modal/connect.config");
const services = require(".//service/index");
const dbService = new DBService();
const app = express();
const { expressjwt, UnauthorizedError } = require("express-jwt");
const { dbName } = require("./modal/db.config"); // 或者使用passport-jwt等替代方案
const SECRET = dbName;
// 定义静态文件目录
const publicDirectoryPath = path.join(__dirname, '/public');


// 使用express.static中间件提供静态文件服务
app.use(express.static(publicDirectoryPath));

app.use(cors());

// parse requests of content-type - application/json
app.use(express.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));


app.use(
  expressjwt({
    secret: SECRET,
    passthrough: false,
    algorithms: ["HS256"],
  }).unless({
    path: [
      /^\/api\/users\/app\/login/,
      /^\/api\/users\/admin\/login/,
      /^\/api\/users\/app\/register/,
      /^\/api\/houses\/app\/list/,
      /^\/api\/houses\/app\/getDetail/,
      /^\/api\/notice\/app\/list/,
      /^\/api\/upload\/fileUpload/,
    ],
  })
);

// 创建一个错误处理中间件
const handleJwtErrors = (err, req, res, next) => {
  if (err.name === "UnauthorizedError") {
    // 如果是由于JWT验证失败导致的错误
    res.status(200).json({
      code: 401,
      data: "身份过期，请重新登录",
      msg: "fail",
    });
  } else {
    // 对于其他类型的错误，让后续的错误处理中间件接手
    next(err);
  }
};

app.use(handleJwtErrors);

//MySQL中间件
app.use(async (req, ctx, next) => {
  try {
    req.mysql = dbService;
    next();
  } catch (err) {
    console.log("mysql error", err);
    ctx.status(500).send("Error connecting to the database.");
  }
});
//service层中间件
app.use(async (req, ctx, next) => {
  try {
    req.services = services(req);
    next();
  } catch (err) {
    console.log("services error", err);
    ctx.status(500).send("services connecting error.");
  }
});

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

require(".//routes/users.routes")(app);
require(".//routes/notice.routes")(app);
require(".//routes/upload.routes")(app);
require(".//routes/messageBoard.routes")(app);
require(".//routes/houses.routes")(app);
require(".//routes/order.routes")(app);
require(".//routes/analysis.routes")(app);



// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
